#include "CocosPCH.h"
#include "CoCElementTexture.h"

#include "Utility.h"

#define TextureFormat_ARGB8888	0
#define TextureFormat_ARGB4444	2
#define TextureFormat_BGR565	4
#define TextureFormat_AI88		6

CoCElementTexture::CoCElementTexture(void)
{
}


CoCElementTexture::~CoCElementTexture(void)
{
	m_pTexture->release();
    if (m_pTextureData)
        free(m_pTextureData);
}

bool CoCElementTexture::Parse(void *data, CoCSWF *pSWF)
{		
	int nDataPos = 0;
	Utility_ReadValue(&m_cTextureFormat, data, &nDataPos);
	Utility_ReadValue(&m_nWidth, data, &nDataPos);
	Utility_ReadValue(&m_nHeight, data, &nDataPos);	
	
    m_pTexture = new Texture2D();
    m_pTexture->initWithData((char*)data + nDataPos, GetDataSize(), GetTextureFormat(), m_nWidth, m_nHeight, Size(m_nWidth, m_nHeight));

    int nDataSize = GetDataSize();
    m_pTextureData = malloc(nDataSize);
    memcpy(m_pTextureData, (char*)data + nDataPos, GetDataSize());

	return true;
}

int CoCElementTexture::GetTextureBpp()
{
	switch(m_cTextureFormat)
	{
		case TextureFormat_ARGB8888:
			return 32;
		case TextureFormat_ARGB4444:
		case TextureFormat_BGR565:
			return 16;
	}

	return -1;
}

Texture2D::PixelFormat CoCElementTexture::GetTextureFormat()
{
	switch(m_cTextureFormat)
	{
		case TextureFormat_ARGB8888:
			return CCTexture2DPixelFormat::RGBA8888;
        case TextureFormat_ARGB4444:
            return CCTexture2DPixelFormat::RGBA4444;
        case TextureFormat_BGR565:
            return CCTexture2DPixelFormat::RGB565;
		case TextureFormat_AI88:
            return Texture2D::PixelFormat::AI88;
	}

    return Texture2D::PixelFormat::DEFAULT;
}

Texture2D *CoCElementTexture::getTexture()
{
	return m_pTexture;
}

int CoCElementTexture::GetDataSize()
{
	return m_nWidth * m_nHeight * GetTextureBpp() / 8;
}

unsigned short CoCElementTexture::GetWidth()
{
	return m_nWidth;
}

unsigned short CoCElementTexture::GetHeight()
{
	return m_nHeight;
}

void CoCElementTexture::SaveToFile(const char *pName)
{
    RenderTexture* texture = RenderTexture::create(m_pTexture->getContentSize().width, m_pTexture->getContentSize().height);
    texture->beginWithClear(0, 0, 0, 0, 0, 0);

    auto sprite = Sprite::createWithTexture(m_pTexture);
    Director::getInstance()->getRunningScene()->addChild(sprite);

    sprite->setAnchorPoint(Vec2(0, 0));
    sprite->visit();
    texture->end();
    Director::getInstance()->getRenderer()->render();
    Director::getInstance()->getRunningScene()->removeChild(sprite);
    Image* image = texture->newImage();
    std::string strUtf8Name = pName;
    Utility_ConvertGBKToUtf8(strUtf8Name);
    if (image->saveToFile(strUtf8Name.c_str(), false))
    {
        CCLOG("filePath:%s", pName);
        delete image;
    }
    else
    {
        CCLOG("write file error");
    }
}